package com.quanyan.activity.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.quanyan.activity.entity.ActivityDesc;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.entity.ActivityMedia;
import com.quanyan.activity.entity.db.*;
import com.quanyan.activity.mapper.TbActivityDescMapper;
import com.quanyan.activity.mapper.TbActivityMapper;
import com.quanyan.activity.mapper.TbActivityMultimediaMapper;
import com.quanyan.activity.service.ActivityService;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.comment.reqeust.APIRequest;
import com.quanyan.comment.reqeust.ReqUserCollect;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.vo.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ProductServiceImpl
 *
 * @author Li Shuai
 * @date 16/5/26
 */
@Service("activityService")
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private TbActivityMapper activityMapper;
    @Autowired
    private TbActivityMultimediaMapper tbActivityMultimediaMapper;
    @Autowired
    private TbActivityDescMapper tbActivityDescMapper;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActivityInfo saveActivity(ActivityInfo activityInfo) {
        TbActivity tbActivity = new TbActivity();
        copyReqToActivity(activityInfo, tbActivity);
        List<ActivityMedia> activityMediaList = activityInfo.getActivityMediaList();
        Integer activityId = activityMapper.insertSelective(tbActivity);
        insertActivityDesc(activityInfo, activityId);
        TbActivityMultimedia tbActivityMultimedia = null;
        if (CollectionUtils.isNotEmpty(activityMediaList)) {
            for (ActivityMedia activityMedia : activityMediaList) {
                tbActivityMultimedia = new TbActivityMultimedia();
                Integer mediaId = insertMedia(activityId, tbActivityMultimedia, activityMedia);
                tbActivityMultimedia.setId(mediaId);
            }
        }
        activityInfo.setId(activityId);
        return activityInfo;
    }

    public void insertActivityDesc(ActivityInfo activityInfo, Integer activityId) {
        ActivityDesc activityDesc = activityInfo.getActivityDesc();
        TbActivityDesc tbActivityDesc = new TbActivityDesc();
        tbActivityDesc.setAttentionDesc(activityDesc.getAttentionDesc());
        tbActivityDesc.setBodyDesc(activityDesc.getBodyDesc());
        tbActivityDesc.setActivityId(activityId);
        tbActivityDescMapper.insertSelective(tbActivityDesc);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActivityInfo updateActivity(ActivityInfo activityInfo) {
        TbActivity tbActivity = new TbActivity();
        copyReqToActivity(activityInfo, tbActivity);
        List<ActivityMedia> activityMediaList = activityInfo.getActivityMediaList();
        Integer activityId = activityMapper.updateByPrimaryKeySelective(tbActivity);
        ActivityDesc activityDesc = activityInfo.getActivityDesc();
        TbActivityDesc tbActivityDesc = new TbActivityDesc();
        tbActivityDesc.setId(activityDesc.getId());
        tbActivityDesc.setAttentionDesc(activityDesc.getAttentionDesc());
        tbActivityDesc.setBodyDesc(activityDesc.getBodyDesc());
        tbActivityDesc.setActivityId(activityId);
        tbActivityDescMapper.updateByPrimaryKey(tbActivityDesc);
        TbActivityMultimedia tbActivityMultimedia = null;
        if (CollectionUtils.isNotEmpty(activityMediaList)) {
            for (ActivityMedia activityMedia : activityMediaList) {
                tbActivityMultimedia = new TbActivityMultimedia();
                Integer mediaId = activityMedia.getId();
                updateMedia(activityId, tbActivityMultimedia, activityMedia);
                tbActivityMultimedia.setId(mediaId);
            }
        }
        activityInfo.setId(activityId);
        return activityInfo;
    }

    /**
     * 修改活动图片
     */
    public Integer updateMedia(Integer activityId, TbActivityMultimedia tbActivityMultimedia, ActivityMedia activityMedia) {
        tbActivityMultimedia.setId(activityMedia.getId());
        tbActivityMultimedia.setStatus(activityMedia.getState().byteValue());
        tbActivityMultimedia.setActivityId(activityId);
        tbActivityMultimedia.setIsMain(activityMedia.getIsMain().byteValue());
        tbActivityMultimedia.setMultimediaUrl(activityMedia.getImageUrl());
        tbActivityMultimedia.setType(Constants.BYTE_ZERO);
        return tbActivityMultimediaMapper.updateByPrimaryKeySelective(tbActivityMultimedia);
    }

    /**
     * 新增活动图片
     */
    public Integer insertMedia(Integer activityId, TbActivityMultimedia tbActivityMultimedia, ActivityMedia activityMedia) {
        tbActivityMultimedia.setStatus(activityMedia.getState().byteValue());
        tbActivityMultimedia.setActivityId(activityId);
        tbActivityMultimedia.setIsMain(activityMedia.getIsMain().byteValue());
        tbActivityMultimedia.setMultimediaUrl(activityMedia.getImageUrl());
        tbActivityMultimedia.setType(Constants.BYTE_ZERO);
        return tbActivityMultimediaMapper.insertSelective(tbActivityMultimedia);
    }

    private void copyReqToActivity(ActivityInfo reqActivity, TbActivity tbActivity) {
        if (null != reqActivity) {
            tbActivity.setSignStartTime(reqActivity.getSignStartTime());
            tbActivity.setSignEndTime(reqActivity.getSignEndTime());
            tbActivity.setCategoryId(reqActivity.getCategoryId());
            tbActivity.setStartTime(reqActivity.getStartTime());
            tbActivity.setEndTime(reqActivity.getEndTime());
            tbActivity.setExtendName(reqActivity.getExtendName());
            tbActivity.setIsOfficial(reqActivity.getIsOfficial());
            tbActivity.setName(reqActivity.getName());
            tbActivity.setPrice(reqActivity.getPrice());
            tbActivity.setPlaceId(reqActivity.getPlaceId());
            tbActivity.setPlaceUnitId(reqActivity.getPlaceUnitId());
            tbActivity.setStatus(reqActivity.getStatus());
        }
    }

    public int deleteActivityById(Integer activityId) {
        TbActivityMultimediaExample example = new TbActivityMultimediaExample();
        example.createCriteria().andActivityIdEqualTo(activityId);
        List<TbActivityMultimedia> tbActivityMultimedias = tbActivityMultimediaMapper.selectByExample(example);

        if (CollectionUtils.isNotEmpty(tbActivityMultimedias)) {
            for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimedias) {
                tbActivityMultimedia.setIsDelete(Constants.BYTE_ONE);
                tbActivityMultimediaMapper.updateByPrimaryKeySelective(tbActivityMultimedia);
            }
        }

        TbActivityDescExample descExample = new TbActivityDescExample();
        descExample.createCriteria().andActivityIdEqualTo(activityId);
        tbActivityDescMapper.deleteByExample(descExample);

        TbActivity tbActivity = activityMapper.selectByPrimaryKey(activityId);
        tbActivity.setIsDelete(Constants.BYTE_ONE);
        int id = activityMapper.updateByPrimaryKeySelective(tbActivity);
        return id;
    }

    public ActivityInfo queryOneActivityById(Integer activityId) {
        //todo 权限信息
        TbActivity tbActivity = activityMapper.selectByPrimaryKey(activityId);
        //活动说明和注意事项
        ActivityDesc activityDesc = getActivityDesc(activityId);
        //活动图片
        List<TbActivityMultimedia> tbActivityMultimediaList = getTbActivityMultimediaList(activityId);

        ActivityInfo activityInfo = new ActivityInfo();
        BeanCopierUtils.copyProperties(tbActivity, activityInfo);

        List<ActivityMedia> respActivityMediaList = new ArrayList<>();

        for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimediaList) {
            ActivityMedia activityMedia = new ActivityMedia();
            Image image = new Image();
            image.setId(tbActivityMultimedia.getId());
            image.setImageUrl(tbActivityMultimedia.getMultimediaUrl());
            image.setState(tbActivityMultimedia.getStatus().intValue());
            respActivityMediaList.add(activityMedia);
        }
        activityInfo.setActivityMediaList(respActivityMediaList);
        activityInfo.setActivityDesc(activityDesc);
        return activityInfo;
    }

    public List<TbActivityMultimedia> getTbActivityMultimediaList(Integer activityId) {
        TbActivityMultimediaExample example = new TbActivityMultimediaExample();
        TbActivityMultimediaExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        return tbActivityMultimediaMapper.selectByExample(example);
    }

    public ActivityDesc getActivityDesc(Integer activityId) {
        TbActivityDescExample descExample = new TbActivityDescExample();
        descExample.createCriteria().andActivityIdEqualTo(activityId);
        List<TbActivityDesc> descList = tbActivityDescMapper.selectByExample(descExample);
        TbActivityDesc tbActivityDesc = null;
        ActivityDesc activityDesc = new ActivityDesc();
        if (CollectionUtils.isNotEmpty(descList)) {
            tbActivityDesc = descList.get(0);
            BeanCopierUtils.copyProperties(tbActivityDesc, activityDesc);
        }
        return activityDesc;
    }


    public List<ActivityInfo> queryActivityList(List<Integer> activityIdList) {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        TbActivityExample example = new TbActivityExample();
        example.createCriteria().andIdIn(activityIdList).andIsDeleteEqualTo(Constants.BYTE_ZERO);

        TbActivityDescExample descExample = new TbActivityDescExample();
        descExample.createCriteria().andActivityIdIn(activityIdList);
        List<TbActivityDesc> descList = tbActivityDescMapper.selectByExample(descExample);

        List<TbActivity> tbActivityList = activityMapper.selectByExample(example);
        //图片集合
        TbActivityMultimediaExample mediaExample = new TbActivityMultimediaExample();
        TbActivityMultimediaExample.Criteria medaiCriteria = mediaExample.createCriteria();
        medaiCriteria.andActivityIdIn(activityIdList).andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbActivityMultimedia> tbActivityMultimediaList = tbActivityMultimediaMapper.selectByExample(mediaExample);

        List<ActivityInfo> respActivityList = new ArrayList<>();
        ActivityInfo respActivity = new ActivityInfo();
        if (CollectionUtils.isNotEmpty(tbActivityList)) {
            for (TbActivity tbActivity : tbActivityList) {
                BeanCopierUtils.copyProperties(tbActivity, respActivity);
                //设置活动图片列表
                setActivityByMedia(tbActivityMultimediaList, respActivity, tbActivity);
                //设置活动说明
                setActivityByDesc(descList, respActivity, tbActivity);
                respActivityList.add(respActivity);
            }
        }
        return respActivityList;
    }

    public void setActivityByDesc(List<TbActivityDesc> descList, ActivityInfo respActivity, TbActivity tbActivity) {
        if (CollectionUtils.isNotEmpty(descList)) {
            ActivityDesc activityDesc = new ActivityDesc();
            for (TbActivityDesc tbActivityDesc : descList) {
                if (tbActivityDesc.getActivityId() == tbActivity.getId()) {
                    BeanCopierUtils.copyProperties(tbActivityDesc, activityDesc);
                }
            }
            respActivity.setActivityDesc(activityDesc);
        }
    }

    public void setActivityByMedia(List<TbActivityMultimedia> tbActivityMultimediaList, ActivityInfo respActivity, TbActivity tbActivity) {
        List<ActivityMedia> activityMediaList = new ArrayList<>();
        ActivityMedia activityMedia = new ActivityMedia();
        if (CollectionUtils.isNotEmpty(tbActivityMultimediaList)) {
            for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimediaList) {
                if (tbActivityMultimedia.getActivityId().equals(tbActivity.getId())) {
                    BeanCopierUtils.copyProperties(tbActivityMultimedia, activityMedia);
                    activityMediaList.add(activityMedia);
                }
            }
            respActivity.setActivityMediaList(activityMediaList);
        }
    }

    public boolean collectActivity(Map<String, Integer> map) {
        Integer uid = map.get("uid");
        Integer activityId = map.get("activityId");
        Integer type = map.get("type");
        ReqUserCollect reqUserCollect = new ReqUserCollect();
        reqUserCollect.setSystemCode(Constants.ACTIVITY_SYSTEM_CODE);
        reqUserCollect.setBusinessCode(Constants.CLUB_COLLECT_ACTIVITY_BUSINESS_CODE);
        reqUserCollect.setUserId(uid);
        reqUserCollect.setBusinessId(activityId);
        reqUserCollect.setStatus(type); //收藏 取消
        APIRequest apiRequest = new APIRequest();
        if (type.intValue() == Constants.YES) {
            apiRequest.setServicesName(Constants.USERCLIENT_USERCOLLECT);
        } else {
            apiRequest.setServicesName(Constants.USERCLIENT_CANCLEUSERCOLLECT);
        }
        apiRequest.setRequestData(reqUserCollect);
        APIResponse<?> apiResponse = null;//userClient.process(apiRequest);
        if (!apiResponse.isRet()) {
            return false;
        }
        APIResponse<Integer> response = new APIResponse<>();
        BeanCopierUtils.copyProperties(apiResponse, response);
        if (apiResponse.getErrcode() == ApiResponseEnum.SUCCESS.getId()) {
            response.setData(Constants.IS_YES);
            //todo 增加/取消收藏活动放redis
        } else {
            return false;
        }
        return true;
    }


}
